﻿//素金购物车
var scrollToph;
var app_url=location.origin;

(function () {
    var cart = {
        init: function () {
            
            var num = 0;//选中的行数
            var rmb = 0;//每卡
            var total = 0;//总价
            this.loadCart();
            this.bindEvents();
        },
        bindEvents: function () {
            var self = this;
             //导航栏的选中
             $('.wrapper').navbarscroll();
            $("#categories li").eq(5).addClass("cur").siblings().removeClass("cur");
             //跳转页面
             $("#categories a").on("click",function(){
            	var link_url=$(this).attr("data-href");
//          	if(APP){
//          		var appJson={};
//         			appJson.title=$(this).attr("data-title");
//         			appJson.url=app_url+link_url;	
//         			YiYi_APP.showNewPage(JSON.stringify(appJson));
//          	}else{
            		location.href = link_url;
            	//}
            });
            //点击关闭钻石详情
            $(".close-detail-btn").on("click", function (ev) {
                self.closeDatail($(this));
            });
            //移除购物车
            $(".remove-cart-btn").on("click", function (ev) {
            	var catrId = $("#cart .check_list_box span.selected").attr("lang");
            	if($("#cart .check_list_box span").is(".selected")){
            		myApp.confirm('确定移除购物车吗？','',function(){
            		 	self.removeCart(catrId);
            		});
            	}else{
            		myApp.alert("请选择!");
            	}
            });
             //随便逛逛
           $("#go_shop").on("click",function(){
           		var link_url="/Customer/PrimeGold?team=0";
           		if(APP){
            		var appJson={};
            		appJson.title="素金库存";
           			appJson.function_menu="goods_search";
           			appJson.goods_type="6";
           			YiYi_APP.showExistingPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
           });
            //点击证书号
            $(".cert-href").on("click", function (ev) {
                self.showCert($(this));
            });
            //关闭证书
            $(".close-cert-box-btn").on("click", function (ev) {
                $(".cert-bg-box").hide();
            });
            //点击看详情
            $("#cart").on("click",".product-href", function (ev) {
            	var _id =  $(this).attr("lang");
            	var link_url="/Customer/PrimeGoldDetails/?ID="+_id+"&team=0";
            	if(APP){
            		var appJson={};
           			appJson.title="素金详情";
           			appJson.url=app_url+link_url;	
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
            });
            //点击全选
			$("#checkbox_check_all").on("click",function(){
				$(this).toggleClass("selected")
				if($(this).hasClass("selected")){
					$(".check_list_box").children("span").addClass("selected");
					$(".check_list_box span.selected").each(function (i, item) {
						var pre = parseFloat($(item).closest("figure").find(".first").text());//当前点击行的每卡
    					var totalprice = parseFloat($(item).closest("figure").find(".totalprice").text());
						self.countCheck(1,pre,totalprice);
					});		
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					self.countCheck(0,0,0);//取消
				}
			});
			//列表的勾选框
			$("#cart").on("click",".check_list_box",function(){
				$(this).children("span").toggleClass("selected");
				var pre = parseFloat($(this).closest("figure").find(".first").text());//当前点击行的每卡
				var totalprice = parseFloat($(this).closest("figure").find(".totalprice").text());
				//判断是否全选
				var length=$("#cart .check_list_box span.checkbox").length;
				var checkLength=$("#cart .check_list_box span.selected").length;
				if(length==checkLength){
					$("#checkbox_check_all").addClass("selected");
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}				
				if($(this).children("span").hasClass("selected")){
					self.countCheck(1,pre,totalprice);//选中
				}else{
					self.countCheck(2,pre,totalprice);//取消
				}
				
			});
			//立即购买
			$("#add_to_order").on("click",function(){
				var cartlistCb = $("#cart .check_list_box span.selected");//tbody中checked的
                if (cartlistCb.length == 0) {
                	myApp.alert("请选择!");
                } else {
                	var orderJson={};
                	orderJson.orderID = [];
                	orderJson.type="prime_golds";
		            for (var i = 0; i < cartlistCb.length; i++) {
		               orderJson.orderID.push(cartlistCb[i].lang);
		            }		           
		            if(APP){
		            	var appJson={};
		            	appJson.title="确认下单";
		            	appJson.url=app_url+"/Customer/SubmitDiaOrder?type=6";
		            	appJson.content=JSON.stringify(orderJson);
		            	YiYi_APP.submitOrder(JSON.stringify(appJson))
		            }else{
		            	var action="/Customer/SubmitDiaOrder?type=6";
					  	form = $("<form method='post' id='params_form' action='"+action+"'>"+
					   	"<input type='text' value='"+JSON.stringify(orderJson)+"' name='params'></form>")
						$("#form_box").html(form);
						$("#params_form").submit();
		            }
                }
			});
        },


        //绑定数据
        bindingCart: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false || _result["msginfo"].rows.length==0) {//获取购物车失败
                $(".null-cart-tip").show();//显示空购物车提示
                $("#cart").hide();//隐藏购物车列表，主要是隐藏列表的边框线

            } else {  //获取购物车成功
                $("#cart").show();//显示购物车内容
                _result = _result["msginfo"].rows;//object;//object  
                 $("#totalCart").html(_result.length);
                var figures = "";//多行数据
                for (var i = 0; i < _result.length ; i++) {//_result.length
                    var figcaption = "";//多列
                    var figure = "";//单行
                    var row=_result[i];
                    //绑定数据
                    figcaption += "<figcaption class='product-parameter' lang='" + row.ID + "'>"+
                    "<div class='imgList'>"+ShowImgOne(row)+"</div>"+
                    	"<h3><b class='list-num' style='display:none'>" + (i + 1) + "</b>" +
                    	"<b>" + GetText("prime_golds",1,row.Weight,"Weight") + "</b>" +
                    	"<b>" + GetText("prime_golds",1,row.Type,"Type") + "</b><b>" + GetText("prime_golds",1,row.Style,"Style") + "</b>" +
                    	"<b>" + GetText("prime_golds",1,row.Material,"Material") +"</b><b>" + GetText("prime_golds",1,row.IsStock,"IsStock") +"</b><b>" + row.Series + "</b>"+
                    	"<b class='place'>" + row.Country+row.State + "</b>"+
                    "</h3>" +
                    "<div class='product-price'>"+
                    	"<span style='display:none'>总重：" + "<b>" + row.TotalWeight + "</b></span>" +
                    	"<div>金价￥：<b class='totalprice'>" +formatRMBPrice(row.GoldPrice) + "</b></div>"+
                    "</div></figcaption>";
                    figure += "<figure class='product-list' data-time='" + DateTimeFormat(row.UpdateTime) + "'>" +
                      	"<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + row.ID + "'></span></div>"+
                        "<a href='javacript:void(0)' class='product-href' lang='" + row.ID + "' data-sn='" + row.OriginSN + "'>" + figcaption + "</a></figure>";

                    figures += figure;//将单行加到多行
                }

                $("#cart").html(figures);//加入到id为inventory的figures中
                //   @*主题色start*@
                $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
				//  @*主题色end*@

            }

        },

        //加载购物车
        loadCart: function () {
            var self = this;
            myApp.showIndicator();//显示加载中
            var result = {};
            result.CustomerID = CustomerID;//客户ID
            result.PageSize = 1;
            result.PageIndex = 1;
            $.ajax({
                url: "/Team/GetPrimeGoldsCarts",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    self.bindingCart(result);//绑定购物车
                    self.clearTotal();//清空选中统计
                    myApp.hideIndicator();//隐藏加载中

                }
            });
        },
        
     

        //移除购物车
        removeCart: function () {
            var self = this;
            //获取ID值
            var result = {};
            result.CustomerID = CustomerID;//客户ID
			var cartlistCb = $("#cart .check_list_box span.selected");//获取选中的行
			var _IDs = "";
            for (var i = 0; i < cartlistCb.length; i++) {
                if (i == 0)
                    _IDs += cartlistCb[i].lang;
                else
                    _IDs += "," + cartlistCb[i].lang;
            }
            result.EmeraldID = _IDs;
            $.ajax({
                url: "/Customer/RemovePrimeGoldsCart",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象

                    if (_result['msgcode'] == false) {
                        myApp.alert(_result['msginfo']);
                    } else {
                      myApp.alert(_result['msginfo'],function(){
                      	 self.loadCart(); 
                      });                                            
                    }
                }
            });
        },

       
        countCheck:function(type,pre,totalPrice){			
			var price=parseFloat($("#check-total-price").text());
			var pre_price=parseFloat($("#check-m-rmb").text());
			var _num = $(".check_list_box span.selected").length;;	
			if(type==1){//加
				price+=totalPrice
				pre_price+=pre
			}
			if(type==2){//减
				price-=totalPrice
				pre_price-=pre
			}
			if(type==0){
				_num=0;
				price=0;
				pre_price=0;
			}
			$("#check-num").text(_num);
			$("#check-m-rmb").text(parseFloat(pre_price).toFixed(1));
			$("#check-total-price").text(parseFloat(price).toFixed(1));
		},
        //清空统计栏
        clearTotal: function () {
            $("#check-num").html(0);
            $("#check-m-rmb").html(0);
            $("#check-total-price").html(0);
        },
    };
    cart.init();
})();

